import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Request } from 'express';
import { RequriePermissionKey } from 'src/cu-dec/cu-dec';
import { UserService } from 'src/user/user.service';

@Injectable()
export class PermissionGuard implements CanActivate {
  constructor(
    private readonly userService: UserService,
    private readonly reflector: Reflector,
  ) {}
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request: Request = context.switchToHttp().getRequest();

    if (!request.user) return true;

    const res = await this.userService.getPermissionByRolesId(
      request.user.roles,
    );

    const requriePermission = this.reflector.getAllAndOverride(
      RequriePermissionKey,
      [context.getHandler(), context.getClass()],
    );

    if (!requriePermission) return true;

    console.log(requriePermission);

    const permission = [];
    res.forEach((item) => {
      if (item.RoleToPermission.length > 0) {
        item.RoleToPermission.forEach((perItem) => {
          permission.push(perItem);
        });
      }
    });

    for (let i = 0; i < requriePermission.length; i++) {
      const currentPermission = requriePermission[i];
      console.log(currentPermission);
      const found = permission.find(
        (item) => item.permission.name == currentPermission,
      );
      if (found) {
        return true;
      }
    }
    throw new UnauthorizedException('权限不足');
  }
}
